package com.lovi.net_;

import com.lovi.utils.StreamUtils;

import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.util.Scanner;



/**
 * 客户端发送消息给服务端，说明要下载的文件名
 * 得到服务端返回的文件，然后写到“D:\桌面\test\用户下载”中
 */
public class DownloadFileClient {
    public static void main(String[] args) throws IOException {
        //与服务端建立连接
        Socket socket = new Socket(InetAddress.getLocalHost(), 9999);
        //接收用户输入
        System.out.println("请输入要下载的文件名：");
        Scanner scanner = new Scanner(System.in);
        String fileName = scanner.next();
        //把文件名写入到服务端
        socket.getOutputStream().write(fileName.getBytes());
        socket.shutdownOutput();
        //接收服务端返回的文件
        byte[] bytes = StreamUtils.streamToBytes(socket.getInputStream());
        String filePath = "D:\\桌面\\test\\用户下载\\" + fileName+".txt";
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(filePath));
        bos.write(bytes);
        bos.flush();
        System.out.println("文件下载成功！");
        bos.close();
        socket.close();



    }
}
